package com.mmall.common.interceptor;

import com.mmall.common.Const;
import com.mmall.common.ServerResponse;
import com.mmall.pojo.User;
import com.mmall.util.JsonUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

/**
 * Created by Jormin on 2017/5/1.
 */
public class LoginInterceptor implements HandlerInterceptor {
    //进入Handler之前执行
    //返回true表示放行
    //返回false表示拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String[] noLoggingFilter=Const.noLoggingFilter;
        String url=request.getRequestURI();
        for (String s : noLoggingFilter) {
            if (url.indexOf(s) >= 0)  {
                return true;
            }
        }

        HttpSession session=request.getSession();
        User user=(User) session.getAttribute(Const.CURRENT_USER);

        if (user!=null){
            return true;
        }
        PrintWriter out = response.getWriter();
        response.setContentType("application/json;charset=UTF-8");
        ServerResponse<String> result = ServerResponse.createByErrorMessage("用户未登录");
        JsonUtil jsonUtil=new JsonUtil();
        String jsonResult=jsonUtil.toJson(result);
        out.print(jsonResult);
        return false;
    }

    /*
    * 进入Handler方法后，返回modelAndView之前执行
    * 应用场景从modelAndView出发：将公用的模板信息在这里传到视图层
    * 也可以统一指定试图
    * */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("doing Handler");
    }

    /*
    * 执行Handler之后执行
    * 可统一异常处理
    * 也可统一日志处理
    * */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,Object o,Exception e) throws Exception {


    }


}

